//GEN-BEGIN:Client
/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2010 Oracle and/or its affiliates. All rights reserved.
 *
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
 * Other names may be trademarks of their respective owners.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common
 * Development and Distribution License("CDDL") (collectively, the
 * "License"). You may not use this file except in compliance with the
 * License. You can obtain a copy of the License at
 * http://www.netbeans.org/cddl-gplv2.html
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
 * specific language governing permissions and limitations under the
 * License.  When distributing the software, include this License Header
 * Notice in each file and include the License file at
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the GPL Version 2 section of the License file that
 * accompanied this code. If applicable, add the following below the
 * License Header, with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * If you wish your version of this file to be governed by only the CDDL
 * or only the GPL Version 2, indicate your decision by adding
 * "[Contributor] elects to include this software in this distribution
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
 * single choice of license, a recipient has the option to distribute
 * your version of this file under either the CDDL, the GPL Version 2 or
 * to extend the choice of license to its licensees as provided above.
 * However, if you add GPL Version 2 code and therefore, elected the GPL
 * Version 2 license, then the option applies only if the new code is
 * made subject to such option by the copyright holder.
 *
 * Contributor(s):
 *
 * Portions Copyrighted 2009 Sun Microsystems, Inc.
 */
/**
 * This file is generated. Please do not change
 */
package UpperMidletPackage;

import java.util.*;
import java.io.*;
import javax.microedition.io.*;

/**
 *
 */
public class WebToMobileClient {

    /**
     * The URL of the servlet gateway
     */
    private String serverURL;
    /**
     * The session cookie of this client
     */
    private String sessionCookie;
    /**
     * Empty array used for no-argument calls, and to represent the value "void"
     */
    private final static Object[] _ = new Object[0];

    /**
     * Constructs a new WebToMobileClient and initializes the URL to the servlet
     * gateway from a hard-coded value.
     */
    public WebToMobileClient() {
        this("http://localhost:8080/ToUpperServlet/servlet/pl.kgierlicka.toupper.web.servlet.WebToMobileServlet");
    }

    /**
     * Constructs a new WebToMobileClient and initializes the URL to the servlet
     * gateway from the given value
     *
     * @param serverURL URL of the deployed servlet
     */
    public WebToMobileClient(String serverURL) {
        this.serverURL = serverURL;
    }

    public String toUpper(String text) throws IOException {
        Object params[] = new Object[]{
            (String) text
        };
        int paramIDs[] = new int[]{
            1
        };
        return (String) invokeServer(1, params, paramIDs);
    }

    /**
     * This method performes a dynamic invocation on the server. It is generic
     * in order to reduce the code size.
     *
     * @param requestID The id of the server service (method) we wish to invoke.
     * @param parameters The parameters that should be passed to the server
     * (type safety is not checked by this method!)
     * @param returnType Is used to indicate the return type we should read from
     * the server
     * @return The return value from the invoked service
     * @exception IOException When a communication error or a remove exception
     * occurs
     */
    private Object invokeServer(int requestID, Object[] parameters, int[] paramIDs) throws IOException {
        HttpConnection connection = (HttpConnection) Connector.open(serverURL);
        connection.setRequestMethod(HttpConnection.POST);
        connection.setRequestProperty("Content-Type", "application/octet-stream");
        connection.setRequestProperty("Accept", "application/octet-stream");

        if (sessionCookie == null) {
            // if this is the first time this client contatcs the server,
            // verify that the version matches
            connection.setRequestProperty("version", "???");
        } else {
            connection.setRequestProperty("cookie", sessionCookie);
        }

        DataOutputStream output = connection.openDataOutputStream();

        // Write invocation code
        output.writeShort(1);

        /*
         * Write the byte signifying that only one call is being made.
         */
        // TODO This is not reflected on server now
        //output.writeShort(1 /* one call to be made to the server */);

        output.writeInt(requestID);
        for (int i = 0; i < parameters.length; i++) {
            writeObject(output, parameters[i], paramIDs[i]);
        }

        output.close();

        int response;
        try {
            response = connection.getResponseCode();
        } catch (IOException e) {
            throw new IOException("No response from " + serverURL);
        }
        if (response != 200) {
            throw new IOException(response + " " + connection.getResponseMessage());
        }
        DataInputStream input = connection.openDataInputStream();
        String sc = connection.getHeaderField("set-cookie");
        if (sc != null) {
            sessionCookie = sc;
        }
        short errorCode = input.readShort();
        if (errorCode != 1) {
            // there was a remote exception
            throw new IOException(input.readUTF());
        }

        Object returnValue = readObject(input);

        input.close();
        connection.close();
        return returnValue;
    }

    /**
     * Serializes object to the stream with given type id
     *
     * @param out
     * @param o object to be serialized to the stream
     * @param id idetification code of the serialized object
     */
    private void writeObject(DataOutputStream out, Object o, int id) throws IOException {
        if (o == null) {
            // write null type to the stream
            out.writeShort(-1);
            return;
        }
        switch (id) {
            case 1:
                // String
                out.writeShort(1);
                out.writeUTF((String) o);
                break;
            default:
                // default if a data type is not supported
                throw new IllegalArgumentException("Unsupported parameter type: " + o.getClass());
        }
    }

    private static Object readObject(DataInput in) throws IOException {
        int type = in.readShort();
        Object result;
        switch (type) {
            case 1:
                // String
                result = in.readUTF();
                return result;
            case -1: /*
                 * NULL
                 */
                return null;
        }
        throw new IllegalArgumentException("Unsupported return type (" + type + ")");
    }
}
//GEN-END:Client
